package com.lujianfei.business.widget;

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;
import javax.swing.Timer;

import com.lujianfei.business.base.OnDrawListener;

public class DrawPanel extends JPanel {

	List<OnDrawListener> mOnDrawListeners = new ArrayList<>();
	final int delay = 100;
	Timer timer;

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		paintAllObject(g);
	}

	public void paintAllObject(Graphics g) {
		for (OnDrawListener onDrawListener : mOnDrawListeners) {
			onDrawListener.paint(g);
		}
	}
	
	public void updateAllObject() {
		for (OnDrawListener onDrawListener : mOnDrawListeners) {
			onDrawListener.update();
		}
	}

	public void addDrawObject(OnDrawListener object) {
		mOnDrawListeners.add(object);
	}

	public void removeDrawObject(OnDrawListener object) {
		mOnDrawListeners.remove(object);
	}
	
	ActionListener listener = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			updateAllObject();
			repaint();
		}
	};

	public void start() {
		if (null == timer) {
			timer = new Timer(delay, listener);
			timer.setRepeats(true);
			timer.start();
		} else if (!timer.isRunning()) {
			timer.restart();
		}
	}

	public void pause() {
		if (null != timer) {
			timer.stop();
		}
	}
	
	public void stop() {
		if (null != timer) {
			timer.stop();
		}
	}
}
